<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 头部警告 -->
      <el-alert title="注意：只运行为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
      <!-- 选中商品分类 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选中商品分类：</span>
          <!-- 选中商品分类的级联选择器配置对象 -->
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="CateChanged"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 商品分类标签 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加动态参数按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBTnDisable"
            @click="addDialogVisible=true"
          >添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot:default="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag @close="handleClose(i,scope.row)" v-for="(item, i) in scope.row.attr_vals" :key="i" closable>{{ item }}</el-tag>
                <!-- 输入文本框 -->
                <el-input
                class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot:default="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加静态属性按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBTnDisable"
            @click="addDialogVisible=true"
          >添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot:default="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag @close="handleClose(i,scope.row)" v-for="(item, i) in scope.row.attr_vals" :key="i" closable>{{ item }}</el-tag>
                <!-- 输入文本框 -->
                <el-input
                class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot:default="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加'+titleTxt"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 添加参数的对话框 -->
      <el-form :model="addFrom" :rules="addFromRules" ref="addFromRef" label-width="100px">
        <el-form-item :label="titleTxt" prop="attr_name">
          <el-input v-model="addFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="'修改'+titleTxt"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 添加参数的对话框 -->
      <el-form :model="editFrom" :rules="editFromRules" ref="editFromRef" label-width="100px">
        <el-form-item :label="titleTxt" prop="attr_name">
          <el-input v-model="editFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //  商品分类列表数据
      cateList: [],
      //   指定级联选择器的配置对象
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover"
      },
      //   选中框双向绑定到的数据
      selectedKeys: [],
      //   被激活的页签名称
      activeName: "many",
      //   动态参数数据
      manyTableData: [],
      //   静态属性数据
      onlyTableData: [],
      //   控制添加对话框的显示与隐藏
      addDialogVisible: false,
      //   添加参数的表单对象
      addFrom: {
        attr_name: ""
      },
      // 添加表单的验证规则对象
      addFromRules: {
        attr_name: [
          {
            required: true,
            message: "请输入参数",
            trigger: "blur"
          }
        ]
      },
      //   控制修改对话框的显示与隐藏
      editDialogVisible: false,
      //   修改的表单数据对象
      editFrom: {},
      // 添加修改表单的验证规则对象
      editFromRules: {
        attr_name: [
          {
            required: true,
            message: "请输入参数",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      //   console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类列表失败");
      }
      this.cateList = res.data;
    },
    // 级联选择框发生变化触发
    CateChanged() { 
      this.getParamsData();
    },
    // tab 页签点击事件
    handleTabClick() {
      this.getParamsData();
    },
    // 获取分类的动态参数和静态属性
    async getParamsData() {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return;
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cataId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数分类列表失败");
      }
      //   获取attr_vals并转换为数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // 控制文本框的显示与隐藏
         item.inputVisible = false
         item.inputValue = ''
        // console.log(item.attr_vals);
      });
    //   console.log(res.data);

      if (this.activeName === "many") {
        this.manyTableData = res.data;
      }
      this.onlyTableData = res.data;
    },
    // 清空重置表单
    addDialogClosed() {
      this.$refs.addFromRef.resetFields();
    },
    // 点击按钮添加参数
    addParams() {
      this.$refs.addFromRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.cataId}/attributes`,
          {
            attr_name: this.addFrom.attr_name,
            attr_sel: this.activeName
          }
        );
        // console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error("添加参数分类列表失败");
        }
        this.$message.success("添加参数成功");
        this.addDialogVisible = false;
        this.getParamsData();
      });
    },
    // 点击按钮，展示修改对话框
    async showEditDialog(attrid) {
      // 查询当前参数的信息
      const {
        data: res
      } = await this.$http.get(
        `categories/${this.cataId}}/attributes/${attrid}`,
        { params: { attr_sel: this.activeName } }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数信息失败");
      }
      this.editFrom = res.data;
      this.editDialogVisible = true;
    },
    // 重置编辑输入框
    editDialogClosed() {
      this.$refs.editFromRef.resetFields();
    },
    // 点击按钮修改参数信息
    editParams() {
      this.$refs.editFromRef.validate(async valid => {
        if (!valid) return;
        const {
          data: res
        } = await this.$http.put(
          `categories/${this.cataId}/attributes/${this.editFrom.attr_id}`,
          { attr_name: this.editFrom.attr_name, attr_sel: this.activeName }
        );
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error("修改信息失败");
        }
        this.$message.success("修改信息成功");
        this.getParamsData();
        this.editDialogVisible = false;
      });
    },
    // 文本框失去焦点或者按下enter
    async handleInputConfirm (row){
        // console.log(1111);
        // 控制按钮和文本框的切换
        if (row.inputValue.trim().length === 0){
            row.inputValue = ''
            row.inputVisible = false
            return
        }
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible = false
        // 发起请求保存数据
       this.saveAttrValue(row)
    },
    // 将对attr_vals的操作保存在数据库中
    async saveAttrValue(row){
        const {data: res} = await this.$http.put(`categories/${this.cataId}/attributes/${row.attr_id}`,{
            attr_name:row.attr_name,
            attr_sel:row.attr_sel,
            attr_vals:row.attr_vals.join(' ')
        })

        if (res.meta.status !== 200) {
        return this.$message.error("修改参数信息失败");
        }
        this.$message.success("修改参数信息成功");
    },
    showInput(row){
        row.inputVisible = true
        // 文本框自动获得焦点
        this.$nextTick(() => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    //  删除对应的参数和选项
    handleClose(i,row) {
        row.attr_vals.splice(i,1)
        this.saveAttrValue(row)
    }
  },
  computed: {
    //   如果按钮需要被禁用，则放回true,否则返回false
    isBTnDisable() {
      if (this.selectedKeys.length !== 3) {
        return true;
      }
      return false;
    },
    //   当前三级分类的ID
    cataId() {
      if (this.selectedKeys.length === 3) return this.selectedKeys[2];
      return null;
    },
    //  动态计算激活标题的文本
    titleTxt() {
      if (this.activeName === "many") {
        return "动态参数";
      }
      return "静态属性";
    }
  }
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 20px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
    width: 150px;
}
</style>
